# Create your views here.
#from l2ldjango.apps.blog.views import *
from l2ldjango.apps.personalblog.models import *
from l2ldjango.apps.personalblog.forms import *
from django.template import RequestContext 
from django.shortcuts import render_to_response, get_object_or_404
from l2ldjango.settings import DATABASES
from django.shortcuts import *
from django.contrib.auth.decorators import login_required
from l2ldjango.apps.personalblog.ssldecorator import *
from l2ldjango.apps.usermanagement.models import *

def runquery(qry):
    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost",DATABASES['default']['USER'],DATABASES['default']['PASSWORD'],DATABASES['default']['NAME'] )
    
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    
    # execute SQL query using execute() method.
    cursor.execute(qry)
    
    # Fetch a single row using fetchone() method.
    #data = cursor.fetchone()
    
    #print "Database version : %s " % data
    
    # disconnect from server
    db.close()

@login_required
def view_all(request):
    #blogs=Forum.objects.filter(status=3).order_by("-creation_date")
    #if request.user.id:
        #blogs=PersonalBlog.objects.filter(is_public=1).order_by("-creation_date")
    #else:
    blogs=PersonalBlog.objects.filter(is_public=1).order_by("-creation_date")
    friends_obj=Friends.objects.filter(initiator=request.user.id,status="APPROVED")
    friends_list=[x.receiver.id for x in friends_obj]
    variables = RequestContext(request,{'friends_list':friends_list,'blogs':blogs})    
    #return HttpResponse(blogs);
    return render_to_response('personalblog/view_personalblog.html',variables) 

@login_required
def editPersonalBlog(request,blogid):
    blog=PersonalBlog.objects.get(id=blogid)
    blogid=blog.id
    if blog.added_by.id==request.user.id:
        if request.method == 'POST':
            form=PersonalBlogForm(request.POST,instance=blog)
            if form.is_valid():
                form.save()
                title="Updated Successfully."
                message="Post Updated."
                variables = RequestContext(request,{'title':title,'message':message,'blogid':blogid,'form':form})    
                return render_to_response('personalblog/edit_personalblog.html',variables) 
            else:
                err=form.errors                
                title="Error Saving"                
                #message="You are not the author of blog which you are tying to edit."
                variables = RequestContext(request,{'title':title,'blogid':blogid,'form':form,'message':err})    
                return render_to_response('personalblog/edit_personalblog.html',variables)
        else:
            form=PersonalBlogForm(instance=blog)
            title="Edit"
            #message="You are not the author of blog which you are tying to edit."
            variables = RequestContext(request,{'title':title,'blogid':blogid,'form':form})    
            return render_to_response('personalblog/edit_personalblog.html',variables)
        #do somentihg
    else:
        title="Permission denied."
        message="You are not the author of blog which you are tying to edit."
        variables = RequestContext(request,{'title':title,'message':message})    
        return render_to_response('pages/success_page.html',variables) 

#@secure_required    
@login_required
def view_personalblog(request,slugname):
    blogs=PersonalBlog.objects.get(slug=slugname)
    form=CommentForm()
    variables = RequestContext(request,{'blogs':blogs,'title':blogs.title,'form':form})    
    #return HttpResponse(blogs);
    return render_to_response('personalblog/single_personalblog.html',variables) 
   
@login_required
def addQuestion(request):
    if request.method == 'POST':
        form = PersonalBlogForm(request.POST)
        if form.is_valid():
            qs=form.save()
            qs_obj=PersonalBlog.objects.get(pk=qs)
            qs_obj.added_by=request.user
            qs_obj.is_public=True
            qs_obj.save()
            blogs=PersonalBlog.objects.filter(is_public=1).order_by("-creation_date")
            variables = RequestContext(request,{'blogs':blogs,'message':'Successfully Posted.'})    
            return render_to_response('personalblog/view_personalblog.html',variables) 
            
        else:
            errs=form.errors
            variables = RequestContext(request,{'form': form,'message':errs})
            return render_to_response('personalblog/add_personalblog.html',variables)    
            
    else:
        form=PersonalBlogForm() 
        variables = RequestContext(request,{'form':form})    
        return render_to_response('personalblog/add_personalblog.html',variables) 

@login_required   
def commentBlog(request):
    blogid=request.POST['blogid']
    blogs=PersonalBlog.objects.get(id=blogid)
    if request.method=='POST':
        #a=Comments()
        #a.user_id=request.user
        form = CommentForm(request.POST)
        if form.is_valid():             
            f_comment=PersonalBlogComments()
            f_comment.comment=request.POST['comment']  
            f_comment.commented_by=request.user
            f_comment.save() 
                      
            qry='%s%s%s%s%s'%('insert into personalblog_personalblog_blog_comments(personalblog_id ,personalblogcomments_id) values (',blogid,',',f_comment.id,')')
            runquery(qry)
            #blogs.comments=lst
            #blogs.save()             
            formnew = CommentForm()
            variables= RequestContext(request,{'commentmessage':'successfully commented!!','blogs':blogs,'form':formnew})
            return render_to_response('personalblog/single_personalblog.html',variables)
            #return render_to_response('registration/success_page.html',variables)
        else:
            errs=form.errors
            form = CommentForm(request.POST)
            variables = RequestContext(request,{'form': form,'blogs':blogs,'message':errs})
            return render_to_response('personalblog/single_personalblog.html',variables)             